/**
 * Created by kevin on 16/12/23.
 */
var Router = require('koa-router')
var UserService = require('../../services/controllers/user.ctrl')

function register(app) {
    var router = new Router({
        prefix: '/users'
    });

    router.get('/', function *(next) {
        var query = this.request.query;
        try{
            var users = yield *UserService.getUsersWithPaging(query);

            if(!users) {
                this.body = RES.ERROR({}, '用户不存在', 500)
            }else {
                // pwd == user.password? this.body = RES.SUCCESS(user, '返回用户成功', 200): this.body = RES.ERROR({}, '用户登录失败', 500)
                this.body = RES.SUCCESS({
                    count: users.count,
                    rows: JSON.parse(JSON.stringify(users.rows))
                }, '获取用户信息成功!', 200)
            }
        }catch(e) {
            console.log(e);
           this.body = RES.ERROR({}, '运行时异常', 500);
        }
    }).put('/:uid', function *(next) {
        var field = this.request.body.field;
        if(!field) {
            return this.body = RES.ERROR({}, '请求不正确', 400)
        }

        try{
            var result = yield *UserService.updateUserByUid(field);
            if(!result) {
                this.body = RES.ERROR({}, '用户不存在', 404)
            }else {
                console.log(result[0], 'this is user')
                if(result[0] >0) {
                    this.body = RES.SUCCESS({}, '用户信息更新成功', 200)
                }else {
                    this.body = RES.ERROR({}, '系统内部问题', 500)
                }
            }

        }catch(e) {
            console.log(e)
            this.body = RES.ERROR({}, '系统内部问题', 500)
        }
    }).delete('/:uid', function *(next) {
        var uid = this.params['uid']
        try{
            var user = yield *UserService.deleteUserByUid(uid);

            if(user > 0) {
                this.body = RES.SUCCESS({}, '删除成功', 200)
            }else {
                this.body = RES.ERROR({}, '删除失败', 500)
            }
        }catch(e) {
            this.body = RES.ERROR({}, e.errors[0].message, 500)
        }

    }).post('/', function *(next) {
        var field = this.request.body.field;
        console.log(field, 'this is field')
        try {
            var user = yield *UserService.createUser(field);
            console.log(user, 'this is user');
            if(user) {
                this.body = RES.SUCCESS({}, '创建成功', 200)
            } else {
                this.body = RES.ERROR({}, '创建失败', 500)
            }
        }catch(e) {
            console.log(e);
            this.body = RES.ERROR({}, e.errors[0].message, 500)
        }
    });

    app.use(router.routes());
    app.use(router.allowedMethods());
}

module.exports = register;
